<?php
namespace App\Controller;
use Common\Controller\AppbaseController;
use Common\Controller\AppbusinessbaseController;
use Common\Controller\AppbusinessdobaseController;
use Common\Controller\AppmemberbaseController;
use Common\Controller\AppuserbaseController;
use Think\Exception;

class BusinesscheckedController extends AppbusinessdobaseController {
    /**
     * 此类是商户审核通过才调用的类
     */

    /**
     * 增加活动
     */
    public function addActivity(){
        $start_time=I('start_time',0,'intval');
        $end_time=I('end_time',0,'intval');
        $inventory=I('inventory',0,'intval');
        $price=I('price',0,'intval');
        $id=I('id',0,'intval');
        if(!$start_time||!$end_time){
            $this->jsonReturn(0,'缺少时间');
        }
        if($inventory<=0){
            $this->jsonReturn(0,'缺少库存');
        }
        if(!$price||!$id){
            $this->jsonReturn(0,'缺少价格');
        }
        $now=time();
        if($now>$start_time||$now>$end_time||$start_time>=$end_time){
            $this->jsonReturn(0,'开始/结束日期不能小于现在或日期选择有误');
        }
        //一次活动不能超过48
        $d=($end_time-$start_time)/(60*60);
        if(intval($d)>48){
            $this->jsonReturn(0,'活动最长48小时');
        }
        //每周限制次数
        $activityDay=intval(C('ACTIVITY_DAY'));
        $businessService=M('BusinessService')->where(['id'=>$id,'business_id'=>$this->businessId,'is_deleted'=>0])->find();
        if($businessService){
            $service_id=$businessService['service_id'];
            //活动的服务必须是洗车/养护
            if($service_id!=parent::SERVICE_CLEAN){
                $service=M('Service')->where(['id'=>$service_id,'is_deleted'=>0])->find();
                if(!$service){
                    $this->jsonReturn(0,'服务不存在');
                }
                if($service['pid']!=parent::SERVICE_MAINTENANCE){
                    $this->jsonReturn(0,'活动必须是养护或洗车服务');
                }
            }
            //获取上下周一/日
            $start=lt_get_last_monday($start_time);
            $end=lt_get_next_sunday($start_time);
            //开始时间周是否有进行中的活动
            $activity=M('BusinessActivity')->where(['is_deleted'=>0,'business_id'=>$this->businessId,'end_time'=>['EGT',$start_time],'start_time'=>['between',[$start,$end]]])->find();
            if($activity&&($activity['start_time']<$end_time) ){
                $this->jsonReturn(0,'当前时间段已存在活动');
            }
            //每周活动限制次数
            $where['business_id']=$this->businessId;
            $where['start_time']  = array('between',array($start,$end));
            $count=M('BusinessActivity')->where($where)->count();
            if($count>=$activityDay){
                $this->jsonReturn(0,'每周最多发布'.$activityDay.'次活动');
            }
            $data['business_id']=$this->businessId;
            $data['start_time']=$start_time;
            $data['end_time']=$end_time;
            $data['name']=$businessService['name'];
            $data['inventory']=$inventory;
            $data['price']=$price;
            $data['business_service_id']=$id;
            $data['create_time']=$now;
            $result=M('BusinessActivity')->add($data);
            if($result!==false){
                $this->jsonReturn(1,'添加成功');
            }else{
                $this->jsonReturn(0,'添加失败');
            }
        }else{
            $this->jsonReturn(0,'服务不存在');
        }
    }

    /**
     * 获取可促销的商户活动
     */
    public function getActivityServices(){
        //活动的服务必须是洗车/养护
        $services=M('Service')->where(['pid'=>parent::SERVICE_MAINTENANCE,'is_deleted'=>0])->field('id')->select();
        $service_ids=array_column($services,'id');
        $clean=parent::SERVICE_CLEAN;
        array_push($service_ids,"$clean");
        $businessServices=M('BusinessService')->where(['service_id'=>['in',$service_ids],'is_deleted'=>0,'business_id'=>$this->businessId])->field('id,name,price,service_id')->select();
        if($businessServices){
            //组合商户服务
            foreach ($businessServices as $businessService){
                if($businessService['service_id']==parent::SERVICE_CLEAN){
                    unset($businessService['service_id']);
                    $result['clean'][]=$businessService;
                }else{
                    unset($businessService['service_id']);
                    $result['maintenance'][]=$businessService;
                }
            }
            $this->jsonReturn(1,'获取成功',$result);
        }else{
            $this->jsonReturn(1,'没有服务',(object)[]);
        }
    }
    
    /**
     * 获取活动列表
     */
    public function getActivities(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $activities=M('BusinessActivity')->where(['is_deleted'=>0,'business_id'=>$this->businessId])->field('id,name,price,start_time,end_time,order_number')
            ->order('create_time DESC')->limit($start,$this->pageLimit+1)->select();
        if($activities){
            $activities=$this->checkEndPage($activities);
            $this->jsonReturn(1,'获取成功',$activities);
        }else{
            $this->jsonReturn(1,'没有活动',(object)[]);
        }
    }

    /**
     * 获取活动内容
     */
    public function getActivityContent(){
        $content=M('BusinessActivityContent')->where(['business_id'=>$this->businessId])->field('content,image,logo')->find();
        if($content){
            $content['image']=empty($content['image'])?'':$this->uploadPre.$content['image'];
            $content['logo']=empty($content['logo'])?'':$this->uploadPre.$content['logo'];
            $this->jsonUnslashesReturn(1,'获取成功',$content);
        }else{
            $this->jsonReturn(1,'还没有内容',(object)[]);
        }
    }

    /**
     * 新增编辑活动内容
     */
    public function addActivityContent(){
        $data['content']=I('content','');
        $image=I('image');
        $logo=I('logo');
        if(!$data['content']&&!$image&&!$logo){
            $this->jsonReturn(0,'请填写相关内容');
        }
        if($image){
            $data['image']=$this->getSaveImageUrl($image);
        }
        if($logo){
            $data['logo']=$this->getSaveImageUrl($logo);
        }
        $content=M('BusinessActivityContent')->where(['business_id'=>$this->businessId])->find();
        //存在更新，否则新加
        if($content){
            $result=M('BusinessActivityContent')->where(['business_id'=>$this->businessId])->save($data);
        }else{
            $data['business_id']=$this->businessId;
            $result=M('BusinessActivityContent')->add($data);
        }
        if($result!==false){
            $this->jsonReturn(1,'编辑成功');
        }else{
            $this->jsonReturn(0,'编辑失败');
        }
    }

    //删除活动
    public function deleteActivity(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $activity=M('BusinessActivity')->where(['is_deleted'=>0,'business_id'=>$this->businessId,'id'=>$id])->find();
        if($activity){
            $time=time();
            if($activity['end_time']>=$time && $activity['start_time']<=$time){
                $this->jsonReturn(0,'活动正在进行不能删除');
            }else{
                //查找活动是否有未消费订单
                $order=M('OrderActivity')->where(['business_activity_id'=>$id,'status'=>1])->find();
                if($order){
                    $this->jsonReturn(0,'该活动存在未消费的活动订单，不能删除');
                }else{
                    //商户活动删除
                    $result = M('BusinessActivity')->where(['id'=>$id])->save(['is_deleted' => 1]);
                    if ($result !== false) {
                        $this->jsonReturn(1,'删除成功');
                    }else{
                        $this->jsonReturn(0,'删除失败');
                    }
                }
            }
        }else{
            $this->jsonReturn(0,'活动不存在');
        }
    }

    //获取活动订单
    public function getActivityOrders(){
        $id=I('id',0,'intval');
        $page=I('page',0,'intval');
        if($page<=0||!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $orders=M('OrderActivity')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY__ as ba ON ba.id=o.business_activity_id')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=ba.business_service_id')
            ->where(['ba.business_id'=>$this->businessId,'business_is_deleted'=>0,'ba.id'=>$id])
            ->order('o.status,o.create_time DESC')
            ->limit($start,$this->pageLimit+1)
            ->field('ba.name,o.status,o.id,bs.service_id,o.payment')
            ->select();
        if($orders){
            foreach ($orders as &$order){
                $service_name=lt_get_service_full_name($order['service_id']);
                $order['service_name']=$service_name;
                unset($order['service_id']);
            }
            $orders=$this->checkEndPage($orders);
            $this->jsonReturn(1,'获取成功',$orders);
        }else{
            $this->jsonReturn(1,'还没有订单',(object)[]);
        }
    }

    //删除活动订单
    public function deleteActivityOrder(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=M('OrderActivity')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY__ as ba ON ba.id=o.business_activity_id')
            ->where(['ba.business_id'=>$this->businessId,'business_is_deleted'=>0,'o.id'=>$id])
            ->field('o.id,o.status')
            ->find();
        if($order){
            if($order['status']!=2){
                $this->jsonReturn(0,'只有已完成订单才能删除');
            }
            $result=M('OrderActivity')->where(['id'=>$id])->save(['business_is_deleted'=>1]);
            if($result!==false){
                $this->jsonReturn(1,'删除成功');
            }else{
                $this->jsonReturn(0,'删除失败');
            }
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //获取活动订单详情
    public function getActivityOrderDetails(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=M('OrderActivity')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY__ as ba ON ba.id=o.business_activity_id')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=ba.business_service_id')
            ->join('LEFT JOIN __USER__ as u ON u.id=o.user_id')
            ->where(['ba.business_id'=>$this->businessId,'business_is_deleted'=>0,'o.id'=>$id])
            ->field('ba.name,o.status,o.id,bs.service_id,o.payment,u.username,u.phone,o.total,o.lat,o.lng,ba.start_time,ba.end_time')
            ->find();
        if($order){
            $service_name=lt_get_service_full_name($order['service_id']);
            $order['service_name']=$service_name;
            unset($order['service_id']);
            $this->jsonReturn(1,'获取成功',$order);
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //活动订单确认消费
    public function activityComplete(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=M('OrderActivity')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_ACTIVITY__ as ba ON ba.id=o.business_activity_id')
            ->where(['ba.business_id'=>$this->businessId,'business_is_deleted'=>0,'o.id'=>$id])
            ->field('o.status,o.id,ba.start_time,o.user_id,ba.name')
            ->find();
        if($order){
            if($order['start_time']>time()){
                $this->jsonReturn(0,'未开始的活动不能确认消费');
            }
            if($order['status']!=1){
                $this->jsonReturn(0,'只有已支付未消费订单才能确认消费');
            }
            //插入信息表
            $title = '您的' . $order['name'] . '的活动订单已经确认消费';
            lt_add_message($title, $title, $order['user_id']);
            $result=M('OrderActivity')->where(['id'=>$id])->save(['status'=>2]);
            if($result!==false){
                $this->jsonReturn(1,'消费成功');
            }else{
                $this->jsonReturn(0,'消费失败');
            }
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }
    /******/
    //获取服务订单
    public function getOrders(){
        $page=I('page',0,'intval');
        if($page<=0){
            $this->jsonReturn(0,'缺少参数');
        }
        $start=($page-1)*$this->pageLimit;
        $orders=M('Order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->where(['bs.business_id'=>$this->businessId,'business_is_deleted'=>0])
            ->order('o.status,o.create_time DESC')
            ->limit($start,$this->pageLimit+1)
            ->field('o.business_service_name,o.status,o.id,bs.service_id,o.payment')
            ->select();
        if($orders){
            foreach ($orders as &$order){
                $service_name=lt_get_service_full_name($order['service_id']);
                $order['service_name']=$service_name;
                unset($order['service_id']);
            }
            $orders=$this->checkEndPage($orders);
            $this->jsonReturn(1,'获取成功',$orders);
        }else{
            $this->jsonReturn(1,'还没有订单',(object)[]);
        }
    }

    //删除服务订单
    public function deleteOrder(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=M('Order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->where(['bs.business_id'=>$this->businessId,'business_is_deleted'=>0,'o.id'=>$id])
            ->field('o.id,o.status')
            ->find();
        if($order){
            if($order['status']!=3){
                $this->jsonReturn(0,'只有已评价订单才能删除');
            }
            $result=M('Order')->where(['id'=>$id])->save(['business_is_deleted'=>1]);
            if($result!==false){
                $this->jsonReturn(1,'删除成功');
            }else{
                $this->jsonReturn(0,'删除失败');
            }
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //获取服务订单详情
    public function getOrderDetails(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=M('Order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->join('LEFT JOIN __USER__ as u ON u.id=o.user_id')
            ->join('LEFT JOIN __BUSINESS_SERVICE_COMMENT__ as bsc ON bsc.order_id=o.id')
            ->where(['bs.business_id'=>$this->businessId,'business_is_deleted'=>0,'o.id'=>$id])
            ->field('o.business_service_name,o.status,o.id,bs.service_id,o.payment,u.username,u.phone,o.total,o.lat,o.lng,IFNULL(bsc.star,"") as star,IFNULL(bsc.content,"") as content')
            ->find();
        if($order){
            $service_name=lt_get_service_full_name($order['service_id']);
            $order['service_name']=$service_name;
            unset($order['service_id']);
            $this->jsonReturn(1,'获取成功',$order);
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //服务订单确认消费
    public function serviceComplete(){
        $id=I('id',0,'intval');
        if(!$id){
            $this->jsonReturn(0,'缺少参数');
        }
        $order=M('Order')
            ->alias('o')
            ->join('LEFT JOIN __BUSINESS_SERVICE__ as bs ON bs.id=o.business_service_id')
            ->where(['bs.business_id'=>$this->businessId,'business_is_deleted'=>0,'o.id'=>$id])
            ->field('o.status,o.id,o.user_id,o.business_service_name')
            ->find();
        if($order){
            if($order['status']!=1){
                $this->jsonReturn(0,'只有已支付未消费订单才能确认消费');
            }
            //插入信息表
            $title = '您的' . $order['business_service_name'] . '的订单已经确认消费';
            lt_add_message($title, $title, $order['user_id']);
            $result=M('Order')->where(['id'=>$id])->save(['status'=>2]);
            if($result!==false){
                $this->jsonReturn(1,'消费成功');
            }else{
                $this->jsonReturn(0,'消费失败');
            }
        }else{
            $this->jsonReturn(0,'订单不存在');
        }
    }

    //设置提现密码
    public function setBalancePassword(){
        $password=I('password');
        $sms=I('sms');
        if(!$sms){
            $this->jsonReturn(0,'验证码必填');
        }
        if(!$password){
            $this->jsonReturn(0,'密码必填');
        }
        $phone=$this->business['phone'];
        if(!preg_match("/^\w{6,25}$/",$password)){
            $this->jsonReturn(0,'密码必须是6到25位的数字字母下划线');
        }
        $this->checkPhoneCode($phone,$sms);
        $result=M('Business')->where(['id'=>$this->businessId])->save(['pay_password'=>sp_password($password)]);
        if($result!==false){
            $this->jsonReturn(1,'更改成功');
        }else{
            $this->jsonReturn(0,'更改失败');
        }
    }

    //获取提现金额等数据
    public function getBalanceData(){
        $this->jsonReturn(1,'获取成功',['pay_status'=>empty($this->business['pay_password'])?0:1,'balance'=>$this->business['balance']]);
    }

    //商户提现
    public function balance(){
        $price=I('price');
        $price=sprintf('%.2f',$price);
        $data['name']=I('name');
        $data['phone']=I('phone');
        $type=I('type',1,'intval');
        $data['account']=I('account');
        $bank=I('bank');
        $password=I('password');
        if(!$price){
            $this->jsonReturn(0,'金额必填');
        }
        if(!$data['name']){
            $this->jsonReturn(0,'名称必填');
        }
        if(!$data['phone']){
            $this->jsonReturn(0,'电话必填');
        }
        if(!$data['account']){
            $this->jsonReturn(0,'账号必填');
        }
        if(!$type||!$password){
            $this->jsonReturn(0,'缺少密码');
        }
        if(!lt_is_telephone($data['phone'])){
            $this->jsonReturn(0,'手机格式不正确');
        }
        if($this->business['balance']<$price){
            $this->jsonReturn(0,'可提现余额不足');
        }
        if(sp_password($password)!=$this->business['pay_password']){
            $this->jsonReturn(0,'支付密码不正确');
        }
        if($type==1){
            if(!$bank){
                $this->jsonReturn(0,'缺少参数');
            }
            $data['bank']=I('bank');
        }
        $data['business_id']=$this->businessId;
        $data['create_time']=time();
        $data['price']=$price;
        $data['type']=$type;
        //开启事务
        M('BusinessBalance')->startTrans();
        try {
            //插入提现表
            $result = M('BusinessBalance')->add($data);
            if ($result === false) {
                throw new Exception('插入提现表失败！');
            }
            //更改商户可提现余额
            $result = M('Business')->where(['id' => $this->businessId])->setDec('balance',$price);
            if ($result === false) {
                throw new Exception('更改商户可提现余额！');
            }
            M('BusinessBalance')->commit();
            $this->jsonReturn(1,'提现成功');
        } catch (Exception $e) {
            M('BusinessBalance')->rollback();
            $this->jsonReturn(0,$e->getMessage());
        }
    }
}